<?php

namespace app\api\controller;

use app\api\model\Comment;
use app\api\model\Dynamic;
use app\api\model\Users;
use app\api\model\Collect;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use app\api\model\Users as UsersModel;
use app\api\model\Visit;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','my','mycollect','mydynamic','mytopic','userdetail'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('Users center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 编辑资料
     *
     */
    public function editdata()
    {
         //获取登录用户信息  关联标签表
       $userdata = UserModel::with('biaoqian')->where('id',1)->find();
       return $userdata;
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('Users not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('Users not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
//
//    /**
//     * 会员列表
//     *
//     */
//    public function userlist()
//    {
//
//        $model = new UserModel();
//        //获取登录用户信息 拿到性别  如果为男 只推荐女    反之  只推荐男
//        $userlist = $model->userlist($userinfo);
//        return $userlist;
//    }
//
    /**
     * 会员详情
     *
     * $userinfo 当前登录的用户信息
     * $uid 会员列表的会员id
     */
    public function userdetail()
    {
        //uid为会员列表的会员id
        $uid = input('uid');
        $uid = 1;
        $model = new UsersModel();
        $detail = $model->userdetail($uid);
        return json_encode($detail);

//        //将谁看过我写在这里
//        //获取到被访问者的用户信息
//     $data =    Users::where('id',$uid)->find();
//     //看过我 +1
//      $data['visit'] = $data['visit']+1;
//      //将当前的登录用户id加入到被访问者的 谁看过我里面
//       $res =  visit::where(['visit'=>$userinfo['id'],'bevisit'=>$uid])->find();
//       if($res == NULL){
//           $time = time();
//           $list = [
//             'visit'=>$userinfo['id'],
//               'bevisit'=>$uid,
//               'create_time'=>$time
//           ];
//           visit::insert($list);
//       }else{
//           $time = time();
//           $tdata = [
//               'create_time'=>$time
//           ];
//           visit::where(['visit'=>$userinfo['id'],'bevisit'=>$uid])->update($tdata);
//       }

    }
//
    /**
     *
     * 帮他介绍
     */
    public function introduce()
    {

    }
    /**
     * 联系他
     *
     */
    public function contact()
    {
        //获取当前登录用户ID
        $uid = 1;
        if(!isset($uid)){
            //如果查不到当前的登录用户id就跳到登录页面
            redirect('vip/vipreal');
        }
       $userinfo =  UsersModel::where('id',$uid)->field('real')->find();
        if($userinfo['real'] == 'no')
        {
            //如果当前登录用户没有实名跳转到实名
            redirect('vip/vipreal');
        }
    }

    /**
     * 我的
     *
     */
    public function my()
    {
        //获取登录用户的id
      $userinfo =  UsersModel::where('id',1)->find();
      return $userinfo;
    }

    /**
     * 红线数
     *
     */
    public function rednum()
    {
        //获取到当前登录用户
        $uid = 1;
        Users::where('id',$uid)->field('thread')->find();
    }


    /**
     * 收藏我
     *
     */
    public function collect()
    {
        //进入详情页点击收藏按钮  获取到登录用户id及被访问者id
      $data =    $this->userdetail();
        //登录用户id
      $uid = 1;
      $becollect_id = $data['id'];
      $list = [
        'collect_id'=>$uid,
          'becollect_id'=>$becollect_id
      ];
     $res =  Collect::where(['collect_id'=>$uid,'becollect_id'=>$becollect_id])->find();
      if($res == NULL)
      {
          //收藏我
         $collect =  Users::where('id',$becollect_id)->field('collect')->find();
          $collectnum = $collect +1 ;
          Users::where('id',$becollect_id)->update(['collect'=>$collectnum]);
          //添加记录到收藏表
          Collect::insert($list);
      }else{
          Collect::where(['collect_id'=>$uid,'becollect_id'=>$becollect_id])->delete();
      }
    }

    /**
     * 资料完整
     *
     */
    public function ziliao()
    {

    }
//    /**
//     * 我的红娘
//     *
//     */
//    public function red()
//    {
//        //获取客服微信表
//        $res = ServerwxModel::where('user_id',$uid)->find();
//    }

    /**
     * 我的话题
     *
     *
     */
    public function mytopic()
    {
        var_dump(11);
        //获取到当前登录用户id
        $uid = 1;
        //从评论表内查出来登录用户的所有评论
      $list =  Comment::with('topic')->where('user_id',1)->select();
          //再根据查出来的所有话题id查询出话题
        $list = json_encode($list);
        var_dump($list[0]['id']);
        exit();
        var_dump($list['topoc_id']);
        exit();
      return json($list);
    }

    /**
     *
     * 我的收藏
     */
    public function mycollect()
    {
        //获取到当前登录的用户id
        $uid = 1;
        //根据当前登录的用户id查出来当前用户所有的收藏id
    $ids =   Collect::where('collect_id',$uid)->select();
     foreach ($ids['becollect_id'] as $value){
         //遍历到所有的被收藏id后根据id查询用户信息
          $res =  Users::where('id',$value)->find();
       }
       return $res;
    }

    /**
     * 我的动态
     *
     * $uid 当前登录用户id
     */
    public function mydynamic()
    {
        //获取当前登录用户
        var_dump(111);
        $uid = 1;
        //拿到评论表里的user_id再根据用户id查询到头像
       $res =  Dynamic::with('users,comments')->where('user_id',1)->select();
       var_dump($res);

//        $json_string = json_encode($res,true);
//       //获取到评论表的user_id
//       var_dump($json_string);
//       exit();
        return json($res);
    }

}
